﻿<style>
    #roleAuthTable + .layui-table-view .layui-table tbody tr:hover {
        background-color: transparent;
    }
    .model-form .layui-form-label {
        width: 100px;
    }
    .model-form .layui-input-block {
        margin-left: 130px;
    }
    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -20px;
        cursor: pointer;
    }
</style>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">企业：</label>
                                    <div class="layui-input-inline">
                                        <select name="companyInfoId"></select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入名称"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="roleBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                            <button id="roleBtnTemplate" class="layui-btn icon-btn layui-btn-normal">模板下载</button>
                            <button id="roleBtnImport" class="layui-btn icon-btn color-reseda">
                                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx"/>导入
                            </button>
                            <button id="roleBtnExport" class="layui-btn icon-btn color-green">导出</button>
                        </div>
                    </div>
                </div>
            </div>

            <table class="layui-table" id="roleTable" lay-filter="roleTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="roleTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-xs" lay-event="auth">权限</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 表单弹窗 -->
<script type="text/html" id="roleForm">
    <form lay-filter="roleForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>所属企业</label>
            <div class="layui-input-block">
                <select name="companyInfoId" lay-filter="getCompanyInfo" lay-verify="required" required lay-search></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>所属部门</label>
            <div class="layui-input-block">
                <select name="departmentId" lay-filter="getDepartment" lay-verify="required" required lay-search></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input"
                       maxlength="20" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>编码</label>
            <div class="layui-input-block">
                <input name="code" placeholder="请输入编码" type="text" class="layui-input"
                       maxlength="200" lay-verify="required|isOnlyCode" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red"></span>是否生产岗位</label>
            <div class="layui-input-block">
                <input name="isProduce" type="checkbox" lay-skin="switch" value="0" lay-text="是|否"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red"></span>社保基数</label>
            <div class="layui-input-block">
                <input name="socialSecurityBase" placeholder="请输入社保基数" type="text" class="layui-input" maxlength="10" lay-verify="integer" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red"></span>公积金基数</label>
            <div class="layui-input-block">
                <input name="providentFundBase" placeholder="请输入公积金基数" type="text" class="layui-input" maxlength="10" lay-verify="integer" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注" class="layui-textarea" maxlength="200"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="roleFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>
<!-- 接口权限 -->
<script type="text/html" id="authModel">
    <form lay-filter="roleAuthorityForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item open-details-box">
            <label class="layui-form-label">选择权限</label>
            <div class="layui-input-block">
                <div id="LAY-auth-tree-index"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="roleAuthorityFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script type="text/javascript" src="../../../admin/assets/js/jsencrypt.min.js"></script>
<script>
    layui.use(['layer', 'form', 'table', 'util', 'admin', 'config', 'tableX', 'authtree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var admin = layui.admin;
        var config = layui.config;
        var authtree = layui.authtree;

        // 获取企业数据
        admin.req('user/admin/companyInfo/list', {limit:9999}, function (res) {
            if ( res.code==200) {
                var html='<option value="">请选择企业</option>';
                for(var k=0;k<res.data.length;k++){
                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                }
                $("select[name='companyInfoId']").html(html);
                form.render('select');
            } else {
                layer.msg('获取企业失败', {icon: 2, time: 1000});
            }
        }, 'GET');

        //渲染表格
        var insTb = table.render({
            elem: '#roleTable',
            url: config.base + 'user/admin/role/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'},
                {field: 'code', title: '编码'},
                {field: 'name', title: '名称'},
                {field: 'companyInfoName', title: '所属企业'},
                {field: 'departmentName', title: '所属部门'},
                {field: 'isProduce', title: '是否生产岗位', templet: function (d) {
                        return d.isProduce ? "是" : "否";
                    }},
                {field: 'remark', title: '备注'},
                // {field: 'creatorName', sort: true, title: '创建人'},
                {field: 'createTime', sort: true, title: '创建时间'},
                {align: 'center', toolbar: '#roleTableBar', title: '操作'}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
                if(menuButton.indexOf("搜索") == -1){
                    $('.layui-form.toolbar').remove();
                }
                if(menuButton.indexOf("修改") == -1){
                    $("[lay-event='edit']").remove();
                }
                if(menuButton.indexOf("删除") == -1){
                    $("[lay-event='del']").remove();
                }
                if(menuButton.indexOf("权限") == -1){
                    $("[lay-event='auth']").remove();
                }
            }
        });

        // 添加按钮点击事件
        $('#roleBtnAdd').click(function () {
            showEditModel();
        });

        // 搜索按钮点击事件
        /*$('#roleBtnSearch').click(function () {
            var keyword = $('#roleEdtSearch').val();
            table.reload('roleTable', {where: {keyword: keyword},page:{curr:1}});
        });*/
        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });

        // 工具条点击事件
        table.on('tool(roleTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'auth') {  // 权限管理
                showPermDialog(obj.data);
            }
        });

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('user/admin/role/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '600px',
                offset: '65px',
                title: data ? '修改角色' : '添加角色',
                content: $('#roleForm').html(),
                success: function () {
                    form.val('roleForm', data);

                    form.verify({
                        isOnlyCode: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            admin.req('user/admin/role/isOnly', {code:value,id:idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET',false);
                            if(!isOnly){
                                return "编码必须唯一"
                            }
                        },
                        integer: [/^([0-9]\d*|[ \t]*)$/, '格式错误']
                    })

                    // 获取企业数据
                    admin.req('user/admin/companyInfo/list', {limit:9999}, function (res) {
                        if ( res.code==200) {
                            var html='<option value="">请选择企业</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                            }
                            $("form select[name='companyInfoId']").html(html);
                            form.render('select');
                            if(data && data.companyInfoId){
                                form.val('roleForm', data);
                            }
                            form.on('select(getCompanyInfo)', function (res) {
                                if(res.value){
                                    // 获取部门数据
                                    admin.req('user/admin/department/list', {limit:9999, companyInfoId: res.value}, function (res) {
                                        if ( res.code==200) {
                                            var html='<option value="">顶级部门</option>';
                                            for(var k=0;k<res.data.length;k++){
                                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                            }
                                            $("form select[name='departmentId']").html(html);
                                            form.render('select');
                                        } else {
                                            layer.msg('获取部门失败', {icon: 2, time: 1000});
                                        }
                                    }, 'GET');
                                }else{
                                    $("form select[name='departmentId']").html("");
                                    form.render('select');
                                }
                            })
                        } else {
                            layer.msg('获取企业失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    if(data && data.companyInfoId){
                        // 获取部门数据
                        admin.req('user/admin/department/list', {limit:9999, companyInfoId: data.companyInfoId}, function (res) {
                            if ( res.code==200) {
                                var html='<option value="">顶级部门</option>';
                                for(var k=0;k<res.data.length;k++){
                                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                }
                                $("form select[name='departmentId']").html(html);
                                form.render('select');
                                if(data && data.departmentId){
                                    form.val('roleForm', data);
                                }
                            } else {
                                layer.msg('获取部门失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');

                    }

                    // 表单提交事件
                    form.on('submit(roleFormSubmit)', function (d) {
                        layer.load(2);
                        var isProduce = $("form input[name='isProduce']").prop("checked");
                        if(!isProduce){
                            d.field.isProduce=false;
                        }else{
                            d.field.isProduce=true;
                        }
                        var isDeleted = $("form input[name='isDeleted']").prop("checked");
                        if(!isDeleted){
                            d.field.isDeleted=false;
                        }else{
                            d.field.isDeleted=true;
                        }
                        admin.req(data ? 'user/admin/role/update' : 'user/admin/role/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('roleTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 权限管理
        function showPermDialog(data) {
            admin.open({
                type: 1,
                isDetail: true,
                area: '800px',
                offset: '65px',
                title: '角色权限管理',
                content: $('#authModel').html(),
                success: function () {

                    admin.req('user/admin/role/authTree', {roleId: data.id}, function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            var trees = res.data;
                            authtree.render('#LAY-auth-tree-index', trees, {
                                themePath: "/admin/assets/module/authtree/tree_themes/",
                                theme: "auth-skin-default",
                                inputname: 'authority',
                                layfilter: 'lay-check-auth',
                                autowidth: true,
                                openall: true,
                                valueKey: "value",
                                childKey: "children",
                                collapseLeafNode: true,
                            });
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');

                    // 表单提交事件
                    form.on('submit(roleAuthorityFormSubmit)', function (d) {
                        layer.load(2);

                        //获取checked值
                        var checkedData = authtree.getChecked('#LAY-auth-tree-index');

                        //合并 checked button
                        var checkedJson = [];
                        var buttonChecked = {};
                        for(var i = 0; i < checkedData.length; i++) {
                            var checked = {};
                            var split = checkedData[i].split(":");
                            checked.menuId = split.length > 0 ? split[0] : null;

                            checked.roleId = data.id;
                            if(split.length > 1){
                                checked.button = split.length > 1 ? split[1] : null;
                                buttonChecked[checked.menuId] = buttonChecked[checked.menuId] == undefined ? checked.button : buttonChecked[checked.menuId] + "," + checked.button;
                            }
                            checkedJson.push(checked);
                        }

                        //菜单去重并写入合并 checked button
                        var result = [];
                        var obj = {};
                        for(var i =0; i<checkedJson.length; i++){
                            checkedJson[i].isChecked = true;
                            if(!obj[checkedJson[i].menuId]){
                                checkedJson[i].menuButton = buttonChecked[checkedJson[i].menuId] == undefined ? null : buttonChecked[checkedJson[i].menuId];
                                result.push(checkedJson[i]);
                                obj[checkedJson[i].menuId] = true;
                            }
                        }

                        admin.reqJson('user/admin/role/addRoleMenu', result, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('roleTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST');

                        return false;
                    });
                }
            });
        }


        // 模板下载
        $("#roleBtnTemplate").click(function () {
            window.location.href = config.base + "user/admin/role/template";
        })

        // 导入excel
        $('#uploaderInput').on("change", function (e) {
            layer.load(2);
            var formData = new FormData();
            var files = e.target.files;
            let that = $(this);
            formData.append("file", files[0]);
            formData.append("name", files[0].name);//这个地方可以传递多个参数
            $.ajax({
                url: config.base + 'user/admin/role/importExcel',
                data: formData,
                headers: {Authorization: 'Bearer ' + config.getToken()},
                type: "POST",
                processData: false,
                contentType: false,
                success: function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        layer.closeAll('page');
                        setTimeout(_ => {
                            location.reload()
                        }, 1000);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                    that.val('');
                }
            });
        })

        // 导出excel
        $('#roleBtnExport').click(function () {
            var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcLt6aJfWmRid+8Cuirv9Zi8sVfhSJ+pUkL7dC+M1yc+e6zr+PQj8sbl2jV5ZBhF4VwoIHWzFLoxNKSizukUNzumJi1KwhjmbASN2EVBKUhJwmx422oew9WCnZYE9+/T+xF87Diie3uQm+7cYVCpvlpqnf9zMBB0Js9zYjOPtP4wIDAQAB";
            var crypt = new JSEncrypt();
            crypt.setKey(publicKey);
            var token = "Bearer "+config.getToken();
            var tokenLeft = token.substring(0,50);
            var tokenRight = token.substring(50);
            var enc = crypt.encrypt(tokenLeft);
            var access_token = enc+tokenRight;
            access_token = access_token.replaceAll('+', '%2B');
            window.location.href = config.base + "user/admin/role/export?access_token=" + access_token;
        });

    });
</script>